<template>
    <div>
        <div class="filter-container vux-1px-b">
            <div style="flex: 1">
                <x-input
                    v-model="query.search"
                    @on-enter="refresh()"
                    :show-clear="false"
                    placeholder="职位、薪资、工作地 ..."
                >
                    <i class="fa fa-search"
                       slot="label"
                       aria-hidden="true"
                       style="margin-right: .5rem;"></i>
                </x-input>
            </div>
            <div @click="onClearSearchBtnClick"
                 v-if="!cardView.loading && query.search.length"
                 style="padding: 0 1rem;"
            >
                <i class="fa fa-times-circle" aria-hidden="true"></i>
            </div>
            <div class="vux-1px-l" @click="onFilterBtnClick" style="padding: 0 1rem;">
                <i class="fa fa-filter"
                   :class="{active: isFiltered}"
                   aria-hidden="true"></i>
            </div>
        </div>

        <div>
            <JobDetailCard
                v-for="item in cardView.data.results"
                @on-job-is-added="onJobIsAdded"
                :job-detail="item"
            />
            <load-more
                v-if="cardView.data.count"
                :show-loading="loadMore.loading"
                :tip="loadMore.tip"
            />
        </div>

        <FilterPopup
            :query="query"
            @on-filter="onFilter"
            ref="filterPopup"
        />

        <div v-transfer-dom>
            <loading :show="cardView.loading" text="玩命加载中"/>
        </div>

        <msg
            v-if="!cardView.loading && cardView.data.count === 0"
            title="暂时没有任何职位信息"
            icon="info"
        />

        <!-- 悬浮投递按钮 -->
        <div class="jobs-cart-btn-container">
            <button
                class="jobs-cart-btn"
                @click="onJobsCartBtnClick"
                :disabled="!toBeSubmitJobs.length"
            >
                <i class="fa fa-paper-plane" aria-hidden="true"></i>
            </button>
            <badge class="badge" v-if="toBeSubmitJobs.length" :text="toBeSubmitJobs.length"></badge>
        </div>
    </div>
</template>

<script>
    import {
        Flexbox,
        FlexboxItem,
        Search,
        XInput,
        XButton,
        Msg,
        Toast,
        Loading,
        LoadMore,
        Badge,
        TransferDomDirective as TransferDom
    } from 'vux';
    import JobDetailCard from './JobDetailCard';
    import FilterPopup from './FilterPopup';
    import eventBus from '@/event-bus';

    const TO_BE_SUBMIT_JOBS_STORAGE_KEY = 'to_be_submit_jobs_storage_key';

    export default {
        name: 'Home',
        directives: {TransferDom},
        components: {
            Flexbox,
            FlexboxItem,
            FilterPopup,
            JobDetailCard,
            Search,
            XInput,
            XButton,
            Msg,
            Toast,
            Loading,
            LoadMore,
            Badge
        },

        data() {
            return {
                cardView: {
                    loading: false,
                    data: {
                        count: 0,
                        next: null,
                        results: []
                    }
                },

                loadMore: {
                    loading: false,
                    tip: '暂无更多'
                },

                query: {
                    // 筛选
                    start_time: '',
                    end_time: '',
                    working_place: '',
                    department: null,
                    type: null,

                    // 排序
                    ordering: [],

                    // 模糊查询
                    search: ''
                },

                page: {
                    current: 1,
                    pageSize: 2
                },

                toBeSubmitJobs: [] // 已投递职位
            };
        }, // data()

        mounted() {
            this.readToBeSubmitJobs();
            this.refresh();
        },

        computed: {
            // 是否开启过滤
            isFiltered() {
                if (this.query.start_time && this.query.start_time !== '') {
                    return true;
                }
                if (this.query.end_time && this.query.end_time !== '') {
                    return true;
                }
                if (this.query.ordering.length > 0) {
                    return true;
                }
                if (this.query.working_place && this.query.working_place !== '') {
                    return true;
                }
                return this.query.department || this.query.type;
            }
        },

        methods: {
            /**
             * 刷新
             * @param isAppend: 是否为追加模式
             */
            refresh(isAppend) {
                if (!isAppend) {
                    this.cardView.loading = true;
                    // 非追加模式，清空职位列表
                    this.$set(this.cardView.data, 'results', []);
                }

                this.$API.jobs.getAll(this.formatParams())
                    .then(resp => {
                        let data = resp.data.data;
                        data.results = this.filterJobs(data.results);
                        data.results = [...this.cardView.data.results, ...data.results];
                        this.cardView.data = data;
                    }, () => {
                    })
                    .finally(() => {
                        this.cardView.loading = false;
                        this.loadMore.loading = false;
                        this.loadMore.tip = '暂无更多';
                    });
            }, // refresh()

            // 格式化查询条件
            formatParams() {
                let params = Object.assign(
                    this.$clonedeep(this.query),
                    this.page
                );

                params.limit = params.pageSize;
                delete params.pageSize;

                params.offset = (params.current - 1) * params.limit;
                delete params.current;

                params.ordering = params.ordering.join(',');

                return params;
            }, // formatParams()

            // 过滤职位信息
            filterJobs(jobList) {
                return jobList.filter(item => item.status_display === '上架');
            }, // methods

            onClearSearchBtnClick() {
                this.query.search = '';
                this.refresh();
            },

            onFilterBtnClick() {
                this.$refs.filterPopup.open();
            },

            onFilter(filterQueryData) {
                if (filterQueryData) {
                    for (let key in this.query) {
                        this.query[key] = filterQueryData[key];
                    }
                }

                this.page.current = 1;
                this.refresh();
            },

            // 职位被添加到投递列队
            onJobIsAdded() {
                this.readToBeSubmitJobs();
            },

            // 上拉加载
            onScrollBottom() {
                let hasNext = !!this.cardView.data.next;
                if (!hasNext || this.loadMore.loading) {
                    return;
                }

                this.page.current++;
                this.loadMore.loading = true;
                this.loadMore.tip = '玩命加载中';
                this.refresh(true);
            },

            // 点击悬浮投递按钮
            onJobsCartBtnClick() {
                this.$router.push({path: '/profile-edit'});
            },

            saveToBeSubmitJobs() {
                sessionStorage.setItem(TO_BE_SUBMIT_JOBS_STORAGE_KEY, JSON.stringify(this.toBeSubmitJobs));
            },

            readToBeSubmitJobs() {
                let toBeSubmitJobs = sessionStorage.getItem(TO_BE_SUBMIT_JOBS_STORAGE_KEY);
                if (toBeSubmitJobs) {
                    this.toBeSubmitJobs = JSON.parse(toBeSubmitJobs);
                }
            }
        }
    };
</script>

<style lang="less" scoped>
    .filter-container {
        display: flex;
        align-items: center;
        background-color: #fff;

        .clear-search-btn {
        }

        .fa-filter {
            color: #888888;
        }

        .fa-filter.active {
            color: #1aad19;
        }
    }

    .jobs-cart-btn-container {
        position: fixed;
        right: 1rem;
        bottom: 2rem;
        background-color: #fff;
        border-radius: 50%;

        .jobs-cart-btn {
            width: 3.5rem;
            height: 3.5rem;
            font-size: 1.5rem;
            color: #ffffff;
            background-color: #1aad19;
            border: none;
            border-radius: 50%;
            outline: none;

            &:active {
                opacity: .8;
            }

            &[disabled] {
                background-color: #888888;
            }
        }

        .badge {
            position: absolute;
            top: .2rem;
            right: .2rem;
        }
    }
</style>
